package cn.lblbc.webbrowser.utils

import android.content.Context
import android.content.SharedPreferences
import cn.lblbc.webbrowser.models.HistoryItem
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HistoryManager(context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    
    companion object {
        private const val PREFS_NAME = "history_prefs"
        private const val KEY_HISTORY = "history"
        private const val MAX_HISTORY_ITEMS = 100
    }
    
    fun getHistory(): List<HistoryItem> {
        val json = prefs.getString(KEY_HISTORY, null) ?: return emptyList()
        val type = object : TypeToken<List<HistoryItem>>() {}.type
        return try {
            gson.fromJson(json, type)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    fun addHistoryItem(item: HistoryItem) {
        val history = getHistory().toMutableList()
        
        // 检查是否已存在相同URL的记录
        val existingIndex = history.indexOfFirst { it.url == item.url }
        if (existingIndex != -1) {
            // 如果存在，移除旧记录
            history.removeAt(existingIndex)
        }
        
        // 添加新记录到列表开头
        history.add(0, item)
        
        // 如果历史记录超过最大数量，移除最旧的记录
        if (history.size > MAX_HISTORY_ITEMS) {
            history.removeAt(history.size - 1)
        }
        
        saveHistory(history)
    }
    
    fun clearHistory() {
        saveHistory(emptyList())
    }
    
    fun deleteHistoryItem(url: String) {
        val history = getHistory().toMutableList()
        history.removeAll { it.url == url }
        saveHistory(history)
    }
    
    fun formatDate(timestamp: Long): String {
        val date = Date(timestamp)
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return format.format(date)
    }
    
    private fun saveHistory(history: List<HistoryItem>) {
        val json = gson.toJson(history)
        prefs.edit().putString(KEY_HISTORY, json).apply()
    }
}